.TH std::optional::operator->,std::optional::operator* 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::optional::operator->,std::optional::operator* \- std::optional::operator->,std::optional::operator*

.SH Synopsis
   constexpr const T* operator->() const noexcept;   \fB(1)\fP \fI(since C++17)\fP
   constexpr T* operator->() noexcept;               \fB(1)\fP \fI(since C++17)\fP
   constexpr const T& operator*() const& noexcept;   \fB(2)\fP \fI(since C++17)\fP
   constexpr T& operator*() & noexcept;              \fB(2)\fP \fI(since C++17)\fP
   constexpr const T&& operator*() const&& noexcept; \fB(2)\fP \fI(since C++17)\fP
   constexpr T&& operator*() && noexcept;            \fB(2)\fP \fI(since C++17)\fP

   Accesses the contained value.

   1) Returns a pointer to the contained value.
   2) Returns a reference to the contained value.

   The behavior is undefined if *this does not contain a value.

.SH Parameters

   \fI(none)\fP

.SH Return value

   Pointer or reference to the contained value.

.SH Notes

   This operator does not check whether the optional contains a value! You can do so
   manually by using has_value() or simply operator bool(). Alternatively, if checked
   access is needed, value() or value_or() may be used.

.SH Example


// Run this code

 #include <iomanip>
 #include <iostream>
 #include <optional>
 #include <string>

 int main()
 {
     using namespace std::string_literals;

     std::optional<int> opt1 = 1;
     std::cout << "opt1: " << *opt1 << '\\n';

     *opt1 = 2;
     std::cout << "opt1: " << *opt1 << '\\n';

     std::optional<std::string> opt2 = "abc"s;
     std::cout << "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size() << '\\n';

     // You can "take" the contained value by calling operator* on an rvalue to optional

     auto taken = *std::move(opt2);
     std::cout << "taken: " << std::quoted(taken) << "\\n"
                  "opt2: " << std::quoted(*opt2) << ", size: " << opt2->size()  << '\\n';
 }

.SH Output:

 opt1: 1
 opt1: 2
 opt2: "abc", size: 3
 taken: "abc"
 opt2: "", size: 0

   Defect reports

   The following behavior-changing defect reports were applied retroactively to
   previously published C++ standards.

      DR    Applied to              Behavior as published              Correct behavior
   LWG 2762 C++17      operator-> and operator* might be               made noexcept
                       potentially-throwing

.SH See also

   value    returns the contained value
            \fI(public member function)\fP
   value_or returns the contained value if available, another value otherwise
            \fI(public member function)\fP
